package com.aicloud.movies.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.aicloud.movies.entity.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;

@RestController
public class MovieController {

	private final static Logger	logger	= LoggerFactory.getLogger(MovieController.class);

	@Autowired
	private RestTemplate		restTemplate;

	@Autowired
	private LoadBalancerClient	discovery;

	@GetMapping("/user/{id}")
	@HystrixCommand(fallbackMethod = "findByIdFallback", commandProperties = {
			@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "1000"), // 请求1s得不到响应就超时，这里需要根据实际场景设置，一般设置成99.5的交易可成功响应的时间即可
			@HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "10000"), // 统计窗口长度默认10s
			// 使用信号量替代线程池，一般使用线程池
			// @HystrixProperty(name="execution.isolation.strategy",value="SEMAPHORE")
	},
	threadPoolProperties = { 
			@HystrixProperty(name = "coreSize", value = "10"), // 线程池大小,默认10
			@HystrixProperty(name = "maximumSize", value = "-1"),// 等待队列,默认-1,不设置等待队列是为了快速失败
	})
	public User findById(@PathVariable Long id) {
		return this.restTemplate.getForObject("http://aicloud-users/user/" + id, User.class);
	}

	public User findByIdFallback(Long id) {
		User user = new User();
		user.setId(-1L);
		user.setName("降级服务");
		return user;
	}

	@GetMapping("/user-instance")
	public ServiceInstance showInfo() {
		ServiceInstance info = this.discovery.choose("aicloud-users");
		logger.info(info.getServiceId() + ", " + info.getHost() + ", " + info.getPort());
		return info;
	}
}
